package com.leyou.order.util;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.leyou.common.exceptions.LyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class PayHelper {

    @Autowired
    private WXPay wxPay;

    @Autowired
    private WXPayConfigImpl payConfig;

    public String getPayUrl(Long orderId, Long totalFee) {
        // 6个请求参数：
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "乐优商城");
        data.put("out_trade_no", orderId.toString());
        data.put("total_fee", totalFee.toString());

        data.put("spbill_create_ip", payConfig.getSpbillCreateIp());
        data.put("notify_url", payConfig.getNotifyUrl());
        data.put("trade_type", payConfig.getTradeType());

        try {
            // 下单
            Map<String, String> resp = wxPay.unifiedOrder(data);

            // 签名验证
            checkSignature(resp);

            // 业务校验
            checkResult(resp);

            // 获取url
            String url = resp.get("code_url");
            if(StringUtils.isEmpty(url)){
                // 支付链接为空，下单失败。
                throw new RuntimeException("支付链接为空！");
            }
            return url;
        } catch (Exception e) {
            throw new LyException(500, "下单失败", e);
        }
    }

    public void checkResult(Map<String, String> resp) {
        if ("FAIL".equals(resp.get("result_code"))) {
            // 业务失败
            throw new RuntimeException("业务执行失败，原因：" + resp.get("err_code_des"));
        }
    }

    public void checkSignature(Map<String, String> resp){
        boolean isSignatureValid = false;
        try {
            isSignatureValid = WXPayUtil.isSignatureValid(resp, payConfig.getKey(), WXPayConstants.SignType.HMACSHA256);
        } catch (Exception e) {
            throw new RuntimeException("签名有误！");
        }
        if(!isSignatureValid){
            throw new RuntimeException("签名有误！");
        }
    }
}
